﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using FolderBrowserDialog = System.Windows.Forms.FolderBrowserDialog;
using DialogResult = System.Windows.Forms.DialogResult;

namespace FormView.UI.PromptView
{
	public class PromptPathView : IPromptViewControl
	{
		public static readonly string TagName = "path";

		public object GetValue(FrameworkElement element)
		{
			Grid grid = element as Grid;
			TextBox textBox = grid.Children[1] as TextBox;
			return textBox.Text;
		}

		public FrameworkElement GetElement(PromptFormWindow win, string tipText, object value)
		{
			string path = value?.ToString() ?? "";

			Grid grid = new Grid();
			grid.Background = PromptFormWindow.DefaultBgColor;
			grid.RowDefinitions.Add(new RowDefinition());
			grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = GridLength.Auto});
			grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = new GridLength(1, GridUnitType.Star) });
			grid.ColumnDefinitions.Add(new ColumnDefinition(){Width = GridLength.Auto});

			TextBlock textBlock = new TextBlock()
			{
				Padding = new Thickness(2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Text = tipText,
				TextAlignment = TextAlignment.Center
			};
			Grid.SetColumn(textBlock, 0);
			grid.Children.Add(textBlock);

			TextBox textBox = new TextBox()
			{
				Padding = new Thickness(2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Background = new SolidColorBrush(Colors.Transparent),
				Text = path,
				TextAlignment = TextAlignment.Left
			};
			Grid.SetColumn(textBox, 1);
			grid.Children.Add(textBox);

			Button btn = new Button()
			{
				Content = "···",
				Padding = new Thickness(5,2,5,2),
				Foreground = PromptFormWindow.DefaultForeColor,
				Background = new SolidColorBrush(PromptFormWindow.ParseColorStr("#33000000")),
				BorderBrush = new SolidColorBrush(Colors.Transparent),
				BorderThickness = new Thickness(0),
				Margin = new Thickness(0)
			};
			btn.Click += (sender, args) => SelectFolder(textBox);
			Grid.SetColumn(btn, 2);
			grid.Children.Add(btn);

			return grid;
		}

		private void SelectFolder(TextBox textBox)
		{
			FolderBrowserDialog dialog = new FolderBrowserDialog();
			dialog.ShowNewFolderButton = true;
			dialog.Description = "请选择一个文件夹";
			if (dialog.ShowDialog() == DialogResult.OK)
			{
				textBox.Text = dialog.SelectedPath;
			}
		}

		public void OnRenderView(PromptFormWindow promptWindow, FrameworkElement element)
		{
			// ignore
		}
	}
}
